package com.sales.util;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Slf4j
public class ImageFileOssUtil {


    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI1MFQKaqHdzSw";
    private static String accessKeySecret = "szQyLJryhX4yg0uWccBh3TZUpWAEf2";
    private static String bucketName = "hxypic";
    private static OSSClient ossClient;

    private static void init() {
        if (ossClient == null) {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    }

    public static void imageUpload(InputStream inputStream,
                                   String fileKey) throws FileNotFoundException {
        init();
        if (ossClient != null) {
            ossClient.putObject(bucketName, fileKey, inputStream);
        }
        log.info("image upload success .......");
    }

    public static String getImageUrl(String fileKey) {
        init();
        if (ossClient != null) {
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
            URL url = ossClient.generatePresignedUrl(bucketName, fileKey, expiration);
            return url.toString();
        }
        return null;
    }

    public static String getUrl(String fileKey) {
        StringBuffer sb = new StringBuffer();

        sb.append("https://").append(bucketName).append(".").append(endpoint).append("/")
                .append(fileKey);

        return sb.toString();
    }
}
